package cn.hejiang.mamis.web.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import cn.hejiang.mamis.core.entity.PlatSys;
import cn.hejiang.mamis.core.entity.SessionDetails;
import cn.hejiang.mamis.core.service.ContextService;
import cn.hejiang.mamis.core.service.PlatSysService;
import lombok.extern.slf4j.Slf4j;

@Controller
@Slf4j
public class EntryController {
	@Autowired
	ContextService contextService;

	@Autowired
	private PlatSysService platSysService;

	@GetMapping("/")
	public void defaultRoot(HttpServletRequest request, HttpServletResponse response) {
		final SessionDetails session = contextService.getSession(request);
		String sysCode = PlatSys.PLATFORM_CODE;
		try {
			String sysId = session.getCurUser().getDefSysId();
			PlatSys sys = platSysService.getSysById(sysId);
			sysCode = sys.getCode();
		} catch (Exception e) {
			log.warn("Fail to get default system for user: {}", session.getCurUser().getLoginName());
		}

		try {
			response.sendRedirect(request.getContextPath() + "/" + sysCode);
		} catch (IOException e) {
			log.error(e.getLocalizedMessage(), e);
		}
	}

	@GetMapping("/{sysCode:(?!amis|magic|api).+}/**")
	public void systemRoot(HttpServletRequest request, HttpServletResponse response,
			@PathVariable("sysCode") String sysCode) {
		try {
			contextService.setSystemByCode(sysCode);
			request.getRequestDispatcher("/mamis/").forward(request, response);
		} catch (IOException | ServletException e) {
			log.error(e.getLocalizedMessage(), e);
		}
	}

}
